use crate::{client::HttpClient, option::Options, response::Response};
use napi_derive_ohos::napi;
use napi_ohos::{bindgen_prelude::AsyncTask, tokio::runtime::Runtime, *};

pub struct HttpTask {
    option: Options,
}

impl HttpTask {
    pub fn new(option: Options) -> HttpTask {
        HttpTask { option }
    }
}

#[napi]
impl Task for HttpTask {
    type Output = Response;
    type JsValue = Response;

    fn compute(&mut self) -> Result<Self::Output> {
        let rt = Runtime::new()?;
        rt.block_on(async {
            let client = HttpClient::new();
            let resp = client.send_request_inner(&self.option).await?;
            Ok(resp)
        })
    }

    fn resolve(&mut self, _: Env, output: Self::Output) -> Result<Self::JsValue> {
        Ok(output)
    }
}

#[napi]
pub fn send_request_async(option: Options) -> AsyncTask<HttpTask> {
    AsyncTask::new(HttpTask { option })
}
